package com.alibaba.sample.kantiezi.dal.dao.ibatis;

import com.alibaba.sample.kantiezi.dal.dao.OrderDao;
import com.alibaba.sample.kantiezi.dal.dataobject.LineItem;
import com.alibaba.sample.kantiezi.dal.dataobject.Order;

import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;

import java.util.List;

public class IbatisOrderDao extends SqlMapClientDaoSupport implements OrderDao {
    public List getOrdersByUsername(String username) {
        return getSqlMapClientTemplate().queryForList("getOrdersByUsername", username);
    }

    public Order getOrder(int orderId) {
        Order  order           = null;
        Object parameterObject = new Integer(orderId);

        order                  = (Order) getSqlMapClientTemplate()
                                             .queryForObject("getOrder", parameterObject);
        order.setLineItems(getSqlMapClientTemplate()
                               .queryForList("getLineItemsByOrderId",
                                             new Integer(order.getOrderId())));
        return order;
    }

    public void insertOrder(Order order) {
        getSqlMapClientTemplate().update("insertOrder", order);
        getSqlMapClientTemplate().update("insertOrderStatus", order);

        for (int i = 0; i < order.getLineItems().size(); i++) {
            LineItem lineItem = (LineItem) order.getLineItems().get(i);

            lineItem.setOrderId(order.getOrderId());
            getSqlMapClientTemplate().update("insertLineItem", lineItem);
        }
    }
}
